package com.yuuko.yuukoapi.project.limb.controller

import com.yuuko.yuukoapi.common.request.PageParam
import com.yuuko.yuukoapi.common.response.AjaxResult
import com.yuuko.yuukoapi.common.response.None
import com.yuuko.yuukoapi.common.response.SelectOptions
import com.yuuko.yuukoapi.framework.extension.findPage
import com.yuuko.yuukoapi.project.limb.doman.entity.DeviceModel
import com.yuuko.yuukoapi.project.limb.doman.entity.dto.DeviceModelListSpec
import com.yuuko.yuukoapi.project.limb.doman.entity.dto.DeviceModelUpdateInput
import com.yuuko.yuukoapi.model.system.dto.RolesListView
import com.yuuko.yuukoapi.repository.limb.DeviceModelRepository
import com.yuuko.yuukoapi.repository.limb.DeviceRepository
import org.babyfish.jimmer.Page
import org.babyfish.jimmer.sql.ast.mutation.SaveMode
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/limb/device-model")
class DeviceModelController(
    val deviceModelRepository: DeviceModelRepository
) {
    @GetMapping("/list")
    fun getDeviceModelList(
        page: PageParam,
        spec: DeviceModelListSpec
    ): AjaxResult<Page<DeviceModel>> {
        val result = deviceModelRepository.findPage(page, spec)
        return AjaxResult.ok(result)
    }

    @PostMapping
    fun createDeviceModel(
        @RequestBody input: DeviceModelUpdateInput,
    ): AjaxResult<None?> {
        deviceModelRepository.save(input, SaveMode.INSERT_ONLY)
        return AjaxResult.ok()
    }

    @PutMapping("/{id}")
    fun updateDeviceModel(
        @PathVariable id: String,
        @RequestBody input: DeviceModelUpdateInput,
    ): AjaxResult<None?> {
        deviceModelRepository.save(input.toEntity { this.id = id }, SaveMode.UPDATE_ONLY)
        return AjaxResult.ok()
    }

    @DeleteMapping("/{id}")
    fun deleteDeviceModel(@PathVariable id: String): AjaxResult<None?> {
        deviceModelRepository.deleteById(id)
        return AjaxResult.ok()
    }

    @GetMapping("/options")
    fun getRoleOptions(): AjaxResult<List<SelectOptions>> {
        val roles = deviceModelRepository.findAllByStatus(1)
        val result = roles.map { SelectOptions(it.id, it.name) }
        return AjaxResult.ok(result)
    }
}